package com.tucc.hello.leetcode.no1_400.no1_200.no21_40.no28;

/**
 * @author tucc
 * @description todo
 * @package com.tucc.hello.leetcode
 * @date 2021/5/20
 **/
public class Solution {

    public static void main(String[] args) {
        Solution solution = new Solution();
        // "mississippi"
        //"issip"
        String haystack = "mississippi";
        String needle = "issip";
        System.out.println(solution.strStr(haystack, needle));
        System.out.println(haystack.indexOf(needle));
    }

    public int strStr(String haystack, String needle) {
        if ("".equals(needle)) {
            return 0;
        }
        if (needle.length() > haystack.length()) {
            return -1;
        } else if (needle.length() == haystack.length()) {
            if (needle.equals(haystack)) {
                return 0;
            }
            return -1;
        }
        int[] next = makeNext(needle);
        for (int i = 0, j = 0; i < haystack.length(); i++) {
            while (j > 0 && haystack.charAt(i) != needle.charAt(j)) {
                j = next[j - 1];
            }
            if (haystack.charAt(i) == needle.charAt(j)) {
                j++;
            }
            if (j == needle.length()) {
                return i - j + 1;
            }
        }
        return -1;
    }

    public int[] makeNext(String needle) {
        int[] next = new int[needle.length()];
        next[0] = 0;

        for (int i = 1, j = 0; i < needle.length(); i++) {
            while (j > 0 && needle.charAt(j) != needle.charAt(i)) {
                j = next[j - 1];
            }
            if (needle.charAt(i) == needle.charAt(j)) {
                j++;
            }
            next[i] = j;
        }
        return next;
    }


}
